package com.kelvin.oocl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Map;

import com.kelvin.oocl.protocol.Protocol;

public class UserThread extends Thread{
	private Socket socket;
	ObjectOutputStream out;
	ObjectInputStream in;
	private Map<String, UserThread> currentUsers;

	public UserThread(Socket socket,Map<String, UserThread> currentUsers) {
		this.socket = socket;
		this.currentUsers = currentUsers;
	}
	
	@Override
	public void run() {
		try {
			out = new ObjectOutputStream(socket.getOutputStream());
			in = new ObjectInputStream(socket.getInputStream());
			
			while(true){
				System.out.println("ttt");
				Protocol pro1 = (Protocol) in.readObject();
				System.out.println(pro1);
				if(pro1.getType()==1){
					this.currentUsers.put(pro1.getFrom(), this);
//					out.writeObject(pro1);
//					out.flush();
				}else if(pro1.getType()==2){
					for(String name:currentUsers.keySet()){
						if(name.equals(pro1.getTo())){
							ObjectOutputStream ooStream  = currentUsers.get(name).getOut();
							ooStream.writeObject(pro1);
							ooStream.flush();
							break;
						}
					}
				}else if(pro1.getType()==3){//group
					for(String name:currentUsers.keySet()){
						if(name.equals(pro1.getFrom())){
							continue;
						}
						ObjectOutputStream ooStream  = currentUsers.get(name).getOut();
						ooStream.writeObject(pro1);
						ooStream.flush();
					}
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}

	public ObjectOutputStream getOut() {
		return out;
	}

	public void setOut(ObjectOutputStream out) {
		this.out = out;
	}

	public ObjectInputStream getIn() {
		return in;
	}

	public void setIn(ObjectInputStream in) {
		this.in = in;
	}

	public Map<String, UserThread> getCurrentUsers() {
		return currentUsers;
	}
	
	
}
